# -*- coding: utf-8 -*-
import webapp2
import exceptions

from objects import Student, House
from webapp2 import uri_for

Errors = [0] * 100

class DisplayData(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        self.response.write('''<html><body>
        <font face="times" size="4">
        <font face="times" size="5"><strong>Домики:</strong></font><ul>''')
        
        Data, Show = {}, {}
        
        house_query = sorted(list(House.query()), key = lambda house: (house.name, -house.rooms))
        house_amount = 0
        for house in house_query:
            Data[house.name] = [[] for i in range(house.rooms)]
            Show[house.name] = house.show
            house_amount += 1
        
        if house_amount == 0:
            self.response.write('<li>Нет ни одного домика</li>')
        
        student_query = sorted(list(Student.query()), key = lambda student: (student.house, student.room, student.name, student.date))
        student_amount = 0
        for student in student_query:
            Data[student.house][student.room - 1].append(student.name)
            student_amount += 1

        for house in sorted(Data):
            if Show[house]:
                self.response.write(u'''<form action="%s" method="post"><strong>%s:</strong>
                <input type="submit" id="button" name="button" value="Скрыть">
                <input type="hidden" id="house" name="house" value="%s"></form><ul>''' % (uri_for('show house'), house, house))
                for i in range(len(Data[house])):
                    self.response.write('<li>Комната %d:</li><ul>' % (i + 1))
                    if len(Data[house][i]) == 0:
                        self.response.write('<li>Пусто</li>')
                    else:
                        for elem in Data[house][i]:
                            self.response.write('<li>%s</li>' % (elem))
                    self.response.write('</ul>')
                self.response.write('</ul>')
            else:
                self.response.write(u'''<form action="%s" method="post"><strong>%s</strong>
                <input type="submit" id="button" name="button" value="Показать">
                <input type="hidden" id="house" name="house" value="%s"></form></ul>''' % (uri_for('show house'), house, house))
        self.response.write('</ul>')
            
        self.response.write('<strong>Всего домиков: %d</strong><br>' % (house_amount))
        self.response.write('<strong>Всего жильцов: %d</strong><br>' % (student_amount))
        self.response.write('<hr NOSHADE size="5" width = "100%" color=#0000a0>')

        self.response.write("""<br><strong>Добавление:</strong><br>
        Добавить жильца:
        <form action="%s" method="post">
            Имя: <input id="name" type="text" name="name">
            Домик: <input id="house" type="text" name="house">
            Комната: <input id="room" type="text" name="room">
            <input type="submit" name="Добавить" value = "Добавить">
        """ % uri_for('add student'))
        
        if Errors[1]:
            self.response.write('''<br>
            <font color = #c80000>Неправильный формат ввода</font>''')
        elif Errors[4]:
            self.response.write('''<br>
            <font color = #c80000>Домика с таким названием не существует</font>''')
        elif Errors[5]:
            self.response.write('''<br>
            <font color = #c80000>В данном домике не существует комнаты с таким номером</font>''')
        
        self.response.write("""</form>
        Добавить домик:
        <form action="%s" method="post">
            Название: <input id="h name" type="text" name="h name">
            Количество комнат: <input id="number" type="text" name="number">
            <input type="submit" name="Добавить" value = "Добавить">
        """ % uri_for('add house'))
        
        if Errors[0]:
            self.response.write('''<br>
            <font color = #c80000>Неправильный формат ввода</font>''')
        elif Errors[2]:
            self.response.write('''<br>
            <font color = #c80000>В домике не может быть менее одной комнаты</font>''')
        elif Errors[3]:
            self.response.write('''<br>
            <font color = #c80000>Домик с таким названием уже существует</font>''')
        
        self.response.write("""</form><br><strong>Удаление:</strong><br>
        Выселить жильца:<br>
        <form action="%s" method="post">
            Имя: <input id="name" type="text" name="name">
            Домик: <input id="house" type="text" name="house">
            Комната: <input id="room" type="text" name="room">
            <input type="submit" name="Выселить" value = "Выселить">
        """ % uri_for('remove student'))
        
        if Errors[6]:
            self.response.write('''<br>
            <font color = #c80000>Неправильный формат ввода</font>''')
        elif Errors[7]:
            self.response.write('''<br>
            <font color = #c80000>Домика с таким названием не существует</font>''')
        elif Errors[8]:
            self.response.write('''<br>
            <font color = #c80000>В данном домике не существует комнаты с таким номером</font>''')
        elif Errors[9]:
            self.response.write('''<br>
            <font color = #c80000>В данной комнате не живет человек с таким именем</font>''')
    
        self.response.write("""</form>
        Выселить жильцов из комнаты:<br>
        <form action="%s" method="post">
            Домик: <input id="house" type="text" name="house">
            Комната: <input id="room" type="text" name="room">
            <input type="submit" name="Выселить" value = "Выселить">
        """ % uri_for('clear room'))
        
        if Errors[10]:
            self.response.write('''<br>
            <font color = #c80000>Неправильный формат ввода</font>''')
        elif Errors[11]:
            self.response.write('''<br>
            <font color = #c80000>Домика с таким названием не существует</font>''')
        elif Errors[12]:
            self.response.write('''<br>
            <font color = #c80000>В данном домике не существует комнаты с таким номером</font>''')
        
        self.response.write("""</form>
        Выселить жильцов из домика:<br>
        <form action="%s" method="post">
            Название: <input id="house" type="text" name="house">
            <input type="submit" name="Выселить" value = "Выселить">
        """ % uri_for('clear house'))
        
        if Errors[13]:
            self.response.write('''<br>
            <font color = #c80000>Неправильный формат ввода</font>''')
        elif Errors[14]:
            self.response.write('''<br>
            <font color = #c80000>Домика с таким названием не существует</font>''')
        
        self.response.write("""</form>
        Удалить домик:<br>
        <form action="%s" method="post">
            Название: <input id="house" type="text" name="house">
            <input type="submit" name="Удалить" value = "Удалить">
        """ % uri_for('remove house'))
        
        if Errors[15]:
            self.response.write('''<br>
            <font color = #c80000>Неправильный формат ввода</font>''')
        elif Errors[16]:
            self.response.write('''<br>
            <font color = #c80000>Домика с таким названием не существует</font>''')
        
        self.response.write("""</form><br>
        <form action="%s" method="post"><input type="submit" value="Выселить всех жильцов"></form>
        
        <form action="%s" method="post"><input type="submit" value="Очистить таблицу"></form><br>
        
        <font color = #0000b0>После какого-либо действия есть смысл обновить страницу.</font>
        </font>
        </body>
        </html>""" % (uri_for('clear students'), uri_for('clear all')))

class AddHouse(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddHouse, self).__init__(*args, **kwargs)
    
    def post(self, *args, **kwargs):
        Errors[0] = False
        Errors[2] = False
        Errors[3] = False
        try:
            name = unicode(self.request.get('h name'))
            rooms = int(self.request.get('number'))
        except exceptions.ValueError:
            Errors[0] = True
            self.redirect(uri_for('show'))
            return
        if name in list([house.name for house in House.query()]):
            Errors[3] = 1
            self.redirect(uri_for('show'))
            return
        if rooms < 1:
            Errors[2] = 1
            self.redirect(uri_for('show'))
            return
        new_house = House(name = name, rooms = rooms, show = 1)
        new_house.put()
        self.redirect(uri_for('show'))

class AddStudent(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddStudent, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        Errors[1] = False
        Errors[4] = False
        Errors[5] = False
        try:
            name = unicode(self.request.get('name'))
            house = unicode(self.request.get('house'))
            room = int(self.request.get('room'))
        except exceptions.ValueError:
            Errors[1] = True
            self.redirect(uri_for('show'))
            return
        if house not in list([elem.name for elem in House.query()]):
            Errors[4] = True
            self.redirect(uri_for('show'))
            return
        if room < 1 or room > list(House.query())[[elem.name for elem in House.query()].index(house)].rooms:
            Errors[5] = True
            self.redirect(uri_for('show'))
            return
        new_student = Student(name = name, house = house, room = room)
        new_student.put()
        self.redirect(uri_for('show'))
    
class RemoveStudent(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(RemoveStudent, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        Errors[6] = False
        Errors[7] = False
        Errors[8] = False
        Errors[9] = False
        try:
            name = unicode(self.request.get('name'))
            house = unicode(self.request.get('house'))
            room = int(self.request.get('room'))
        except exceptions.ValueError:
            Errors[6] = True
            self.redirect(uri_for('show'))
            return
        if house not in list([elem.name for elem in House.query()]):
            Errors[7] = True
            self.redirect(uri_for('show'))
            return
        if room < 1 or room > list(House.query())[[elem.name for elem in House.query()].index(house)].rooms:
            Errors[8] = True
            self.redirect(uri_for('show'))
            return
        for student in Student.query():
            if student.name == name and student.house == house and student.room == room:
                student.key.delete()
                break
        else:
            Errors[9] = True
        self.redirect(uri_for('show'))

class ClearRoom(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearRoom, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        Errors[10] = False
        Errors[11] = False
        Errors[12] = False
        try:
            house = unicode(self.request.get('house'))
            room = int(self.request.get('room'))
        except exceptions.ValueError:
            Errors[10] = True
            self.redirect(uri_for('show'))
            return
        if house not in list([elem.name for elem in House.query()]):
            Errors[11] = True
            self.redirect(uri_for('show'))
            return
        if room < 1 or room > list(House.query())[[elem.name for elem in House.query()].index(house)].rooms:
            Errors[12] = True
            self.redirect(uri_for('show'))
            return
        for student in Student.query():
            if student.house == house and student.room == room:
                student.key.delete()
        self.redirect(uri_for('show'))

class ClearHouse(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearHouse, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        Errors[13] = False
        Errors[14] = False
        try:
            house = unicode(self.request.get('house'))
        except exceptions.ValueError:
            Errors[13] = True
            self.redirect(uri_for('show'))
            return
        if house not in list([elem.name for elem in House.query()]):
            Errors[14] = True
            self.redirect(uri_for('show'))
            return
        for student in Student.query():
            if student.house == house:
                student.key.delete()
        self.redirect(uri_for('show'))

class RemoveHouse(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(RemoveHouse, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        Errors[15] = False
        Errors[16] = False
        try:
            name = unicode(self.request.get('house'))
        except exceptions.ValueError:
            Errors[15] = True
            self.redirect(uri_for('show'))
            return
        if name not in list([elem.name for elem in House.query()]):
            Errors[16] = True
            self.redirect(uri_for('show'))
            return
        for student in Student.query():
            if student.house == name:
                student.key.delete()
        for house in House.query():
            if house.name == name:
                house.key.delete()
                break
        self.redirect(uri_for('show'))

class ClearStudents(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearStudents, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        for key in Student.query().iter(keys_only=True):
            key.delete()
        self.redirect(uri_for('show'))

class ClearAll(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ClearAll, self).__init__(*args, **kwargs)
    
    def post(self, *args, **kwargs):
        global Errors
        Errors = [0] * 100
        for key in House.query().iter(keys_only=True):
            key.delete()
        for key in Student.query().iter(keys_only=True):
            key.delete()
        self.redirect(uri_for('show'))

class ShowHouse(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ShowHouse, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        house_name = unicode(self.request.get('house'))
        for house in House.query():
            if house.name == house_name:
                new_house = House(name = unicode(house.name), rooms = int(house.rooms), show = int(1 - house.show))
                house.key.delete()
                new_house.put()
                break
        self.redirect(uri_for('show'))